<script setup lang="ts">
import RobotAvatar from '~/assets/img/robot-avatar.png';
import markdownit from 'markdown-it';
import hljs from 'highlight.js';
import type MarkdownIt from 'markdown-it/lib/index.mjs';
import type { MessageType } from '~/types/chat';
import dayjs from 'dayjs';

defineProps<{
    msgList: MessageType[],
}>();

// md renderer
const md: MarkdownIt = markdownit({
    breaks: true,
    highlight: function (str: string, lang: string) {
        if (lang && hljs.getLanguage(lang)) {
            try {
                return '<pre><code class="hljs">' +
                    hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
                    '</code></pre>';
            } catch (_) { }
        }
        return '<pre><code class="hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
    },
});
</script>

<template>
    <ol class="p-2 w-full flex flex-col gap-2 overflow-x-hidden">
        <transition-group name="fade">
            <li class="w-full flex overflow-x-hidden" :class="{ 'flex-row-reverse': item.role === 'user' }"
                v-for="(item, index) in msgList" :key="index">
                <c-avatar-img :src="item.role === 'bot' ? RobotAvatar : ''" class="h-12 aspect-square rounded" />
                <div class="p-2 w-fit overflow-x-hidden">
                    <span class="w-full text-sm text-slate-400" :class="{ 'text-right': item.role === 'user' }">
                        {{ dayjs(item.time).format('YYYY-MM-DD HH:mm:ss') }}
                    </span>
                    <div class="px-3 py-2 w-full rounded-md border border-slate-100 shadow-md overflow-hidden break-words"
                        v-html="md.render(item.content)" />
                </div>
            </li>
        </transition-group>
    </ol>
</template>

<style scoped>
.fade-enter-active,
.fade-leave-active {
    transition: all 800ms 200ms ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
    translate: 0 20%;
}
</style>